package com.example.business.filter;

import com.example.business.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;


@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final UserDetailsService userDetailsService;
    public JwtAuthenticationFilter(UserDetailsService userDetailsService) {
        this.userDetailsService= userDetailsService;
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 从Header获取Token（如"Authorization: Bearer <token>"）
        String token = request.getHeader("Authorization");
        log.info("token: " + token);
        if (token != null) {
            String username = JWTUtil.parseJwtToken(token);
            log.info("username: " + username);
            if (username != null) {
                // Token有效，创建认证对象并放入Security上下文
                // 2. 通过UserDetailsService加载用户信息（含权限）
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                // 3. 获取用户权限集合（已自动转换为GrantedAuthority类型）
                Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();

                UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                        username, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
        chain.doFilter(request, response);
    }

    // 提取Token
    private String extractToken(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            return header.substring(7);
        }
        return null;
    }
}